package com.yang.my.sync.two;

/**
 * 关键字synchronized取得的锁都是对象锁;而不是一段代码(方法)当作锁
 * 那个线程先执行synchronized关键字,那个线程就持有该方法所属对象的锁(LOCK)
 * @Author: Mu_YI
 * @Date: 2019/3/17 20:39
 * @Version 1.0
 */
public class MyThread {

    private int num = 0;

    private synchronized void printNum(String tag){
        try {
            if("a".equals(tag)){
                num = 100;
                System.out.println("tag a is over;set num over ：num:" + num);
                Thread.sleep(2000);
            } else {
                num = 200;
                System.out.println("tag b is over;set num over");
            }
            System.out.println("tag:" +tag +";num:"+num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        final MyThread myThread = new MyThread();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                myThread.printNum("a");
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                myThread.printNum("b");
            }
        });

        t1.start();
        t2.start();

    }
}
